﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using DataObjects.EntityFramework.ModelMapper;
using System.Linq.Dynamic;

namespace DataObjects.EntityFramework.Implementation
{
    public class EntityPointDao : IPointDao
    {
        public Point GetPoint(int PointId)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                return Mapper.Map(context.PointEntities.FirstOrDefault(p => p.PointId == PointId));
            }
        }
        public List<Point> GetPoints(int provinceId, string sortExpression)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var list = new List<Point>();

                var query = context.PointEntities.AsQueryable();
                if (provinceId != 0)
                { 
                    query = query.Where(p => p.ProvinceId == provinceId);
                }


                var points = query.OrderBy(sortExpression, null).ToList();

                list = points.Select(p => Mapper.Map(p)).ToList();
                return list;
            }
        }
        public void InsertPoint(Point point)
        {
            var entity = Mapper.Map(point);

            using (var context = DataObjectFactory.CreateContext())
            {
                context.PointEntities.AddObject(entity);
                context.SaveChanges();

                // update business object with new version and id
                point.PointId = entity.PointId;

                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void UpdatePoint(Point point)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.PointEntities.Where(p => p.PointId == point.PointId).SingleOrDefault();

                entity.PointId = point.PointId;
                entity.ProvinceId = point.ProvinceId;
                entity.Description = point.Description;

                context.PointEntities.ApplyCurrentValues(entity);
                context.SaveChanges();

                // Update business object with new version
                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void DeletePoint(Point point)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.PointEntities.Where(p => p.PointId == point.PointId).SingleOrDefault();
                context.PointEntities.DeleteObject(entity);
                context.SaveChanges();
            }
        }
    }
}
